<template>
  <div>
    <a-card>
      <a-button type="primary" @click="showModal"> <PlusOutlined style="color: #ffff" />新建</a-button>
      <!-- 新建弹框 -->
      <a-modal v-model:visible="isModalVisible" :title="modalTitle" @ok="handleOk()" @visibleChange="handleModalVisibleChange" style="width: 600px">
        <a-form :model="formState" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" ref="formRef" >
          <a-form-item ref="name" label="模型名称:" name="name">
            <a-input v-model:value="formState.name" placeholder="请填写模型名称" />
          </a-form-item>
          <a-form-item label="组态模型:" name="description">
            <a-select v-model:value="formState.description" placeholder="请选择组态模型" @change="fetchDeviceModels">
              <a-select-option v-for="item in configurationlist" :key="item.displayUid" :value="item.displayUid">{{
                item.description
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="组态展示页面:" name="PageName">
            <a-select v-model:value="formState.PageName" placeholder="请选择组态展示页面">
              <a-select-option v-for="item in peviceModelslist" :key="item.index" :value="item.PageId">{{ item.PageName }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="描述:" name="dec">
            <a-textarea v-model:value="formState.dec" />
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 编辑弹框 -->
      <a-modal v-model:visible="iseditModalVisible" title="编辑" @ok="editandleOk()" @visibleChange="handleModalVisibleChange" style="width: 600px">
        <a-form :model="formState" :rules="rules" :label-col="labelCol" ref="formRef" :wrapper-col="wrapperCol">
          <a-form-item ref="name" label="模型名称:" name="name">
            <a-input v-model:value="formState.name" />
          </a-form-item>
          <a-form-item label="模型描述:" name="dec">
            <a-textarea v-model:value="formState.dec" />
          </a-form-item>
          <a-form-item label="组态模型:" name="description">
            <a-select v-model:value="formState.description" placeholder="请选择组态模型" @change="fetchDeviceModels">
              <a-select-option v-for="item in configurationlist" :key="item.configUid" :value="item.displayUid"> 演示应用 </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="组态展示页面:" name="PageName">
            <a-select v-model:value="formState.PageName" placeholder="请选择组态展示页面">
              <a-select-option v-for="item in peviceModelslist" :key="item.index" :value="item.PageId">{{ item.PageName }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="下发格式:" name="MqttSetDataFormat">
            <div class="main">
              <code-mirror v-model="formState.MqttSetDataFormat" basic :lang="lang" style="height: 280px" :extensions="extensions" />
            </div>
          </a-form-item>
        </a-form>
      </a-modal>
      <a-button style="margin-left: 10px" @click="Refresh"> <UndoOutlined />刷新</a-button>
      <a-table :dataSource="dataSources" :columns="columns" bordered style="margin-top: 5px" :custom-row="() => ({ style: { height: '35px' } })">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="EditbulletFrame(record)"><FormOutlined />编辑</a-button>
            <a-button type="link" style="color: #ffa128" @click="GoToDatalist(record)"><UploadOutlined style="color: #ffa128" />数据列表</a-button>
            <a-popconfirm
              title="删除"
              ok-text="确认"
              cancel-text="取消"
              description="你确定要删除吗?"
              @confirm="handleDelete(record)"
              @cancel="cancel"
            >
              <a-button type="link" danger> <DeleteOutlined style="color: red" />删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>
<script setup>
  import { ref, onMounted, reactive } from 'vue';
  import { message } from 'ant-design-vue';
  import { VrtualDeviceApi } from '/@/api/system/VrtualDevice.js';
  import { useRouter } from 'vue-router';
  const router = useRouter();
  // 数据列表跳转页面方法
  const GoToDatalist = (record) => {
      router.push({
        path: '/system/VirtualDevice/VrtualDeviceData',
        query: { muid: record.uuid }, // 查询参数
      });
  };

  // 表格列配置
  const columns = ref([
    {
      title: '序号',
      dataIndex: 'ID',
      key: 'ID',
    },
    {
      title: '模型名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '模型描述',
      dataIndex: 'dec',
      key: 'dec',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 320,
    },
  ]);
  //   列表数据
  const dataSources = ref([]);
  async function DeviceModelList(val) {
    const parms = {
      type: 480,
    };
    try {
      const res = await VrtualDeviceApi.GetVirtualDeviceModelList(parms);
      dataSources.value = res.list;
    } catch (error) {
      console.error('表格数据出错', error);
    }
  }
  // 刷新按钮
  const Refresh = () => {
    DeviceModelList();
    message.success('刷新成功');
  };
  // 组态模型
  const configurationlist = ref([]);
  const selectedDeviceType = ref('');
  const configurationModels = async () => {
    const res = await VrtualDeviceApi.displayModelList();
    if (res && res.list) {
      configurationlist.value = res.list;
    }
  };
  // 组态展示页面
  const peviceModelslist = ref([]);
  const deviceModels = ref([]);
  const fetchDeviceModels = async (val) => {
    const params = {
      muid: val,
    };
    try {
      const res = await VrtualDeviceApi.getDisplayModelLayerData(params);
      if (res && res.layer) {
        peviceModelslist.value = res.layer;
      }
    } catch (error) {
      console.error('出错', error);
    }
  };
  //   编辑弹框
  const isEditMode = ref(false); // 用于判断是否为编辑模式
  const modalTitle = ref('添加');
  const iseditModalVisible = ref(false);
  const EditbulletFrame = (record) => {
    configurationModels(record.PageUUID);
    fetchDeviceModels(record.configUid);
    modalTitle.value = '编辑'; // 点编辑时弹框标题
    isEditMode.value = true; // 设置为编辑模式
    isModalVisible.value = true;
    formState.value = { ...record }; // 填充表单数据
    formState.name = record.name;
    formState.dec = record.dec;
    formState.PageName = record.PageUUID;
    formState.description = record.configUid;
    formState.uuid = record.uuid;
  };
  // 新建弹框
  const isModalVisible = ref(false);
  const showModal = () => {
    modalTitle.value = '添加触发器';
    formState.name = '';
    formState.dec = '';
    formState.PageName = '';
    formState.description = '';
    isModalVisible.value = true;
    configurationModels();
  };
  const formState = reactive({
    name: '', //模型名称
    dec: '', //模型描述
    PageName: '', //组态模型
    description: '', //组态展示页面
  });
  const formRef = ref();
  //   表单校验
  const rules = {
    name: [
      {
        required: true,
        message: '请填写模型名称',
        trigger: 'change',
      },
    ],
    dec: [
      {
        required: true,
        message: '请填写模型名称',
        trigger: 'change',
      },
    ],
  };

  //   新增确认
  const handleOk = async () => {
    try {
      await formRef.value.validate();
      const params = {
        PageUUID: formState.PageName,
        configUid: formState.description,
        name: formState.name,
        dec: formState.dec,
        type: 480,
      };
      const paremsedit = {
        data: {
          PageUUID: formState.PageName,
          configUid: formState.description,
          name: formState.name,
          dec: formState.dec,
          type: 480,
        },
        uuid: formState.uuid,
      };
      if (isEditMode.value) {
        const res = await VrtualDeviceApi.EditVirtualDeviceModel(paremsedit);
        message.success('修改成功');
      } else {
        const res = await VrtualDeviceApi.AddVirtualDeviceModel(params);
        message.success('新建成功');
      }
      DeviceModelList();
      isModalVisible.value = false;
    } catch (error) {
      // 如果校验失败
      console.error('表单验证失败', error);
      message.error('请填写所有必填项');
    }
  };
  // 编辑
//   const editandleOk = async (val) => {
//     try {
//       const parems = {
//         data: {
//           PageUUID: formState.PageName,
//           configUid: formState.description,
//           name: formState.name,
//           dec: formState.dec,
//           type: 480,
//         },
//         uuid: formState.uuid,
//       };

//       DeviceModelList();
//       iseditModalVisible.value = false;
//     } catch (error) {
//       console.error('表单修改失败', error);
//     }
//   };

  // 删除
  async function handleDelete(record) {
    const prams = {
      uuid: record.uuid,
    };
    try {
      const res = await VrtualDeviceApi.DelVirtualDeviceModel(prams);
      message.success('删除成功');
      DeviceModelList();
    } catch (error) {
      console.error('删除失败', error);
    }
  }
  onMounted(() => {
    DeviceModelList();
  });
</script>

<style scoped></style>
